package com.usermanage.DataSourceConfig;



import javax.naming.Name;
import javax.persistence.EntityManager;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef="entityManagerFactoryEos",
        transactionManagerRef="transactionManagerEos",
        basePackages= {"com.usermanage.Mapping", "com.contract.Repository"}) //设置Repository所在位置
public class EOSConfig {
    @Autowired
    @Qualifier("eosSource")
    private DataSource eosSource;
    @Autowired
    private JpaProperties jpaProperties;


    @Bean(name = "entityManagerEos")
    public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
        return entityManagerFactoryEos(builder).getObject().createEntityManager();
    }

    @Primary
    @Bean(name = "entityManagerFactoryEos")
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryEos (EntityManagerFactoryBuilder builder) {
        return builder
                .dataSource(eosSource)
                .properties(jpaProperties.getProperties())
                .packages("com.usermanage.beanParam","com.contract.Bean") //设置实体类所在位置
                .persistenceUnit("eosPersistenceUnit")
                .build();
    }

    @Primary
    @Bean(name = "transactionManagerEos")
    public PlatformTransactionManager transactionManagerEos(EntityManagerFactoryBuilder builder) {
        return new JpaTransactionManager(entityManagerFactoryEos(builder).getObject());
    }

}
